package com.jzoom.zoom.admin.modules;

import com.jzoom.zoom.admin.models.DaoListener;
import com.jzoom.zoom.admin.models.MutilDaoListener;
import com.jzoom.zoom.common.annotations.Inject;
import com.jzoom.zoom.common.annotations.IocBean;
import com.jzoom.zoom.common.annotations.Module;
import com.jzoom.zoom.common.utils.PathUtils;
import com.jzoom.zoom.dao.Dao;
import com.jzoom.zoom.dao.alias.impl.NameAdapterMakerWrap;
import com.jzoom.zoom.dao.alias.impl.ToLowerCaseNameAdapter;
import com.jzoom.zoom.dao.impl.ZoomDao;
import com.jzoom.zoom.dao.provider.DruidDataSourceProvider;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.File;

@Module
public class AdminModule {

    private static final Log log = LogFactory.getLog(AdminModule.class);


    @IocBean
	public DaoListener getDaoListener() {
		return new MutilDaoListener();
	}

    @Inject(config = "zoom.h2")
    private String dbFile;

    private String getDbFile() {
        String dbFile = this.dbFile;
        if (dbFile == null) {
            dbFile = getWebInf();
        } else {
            if (!new File(dbFile + ".h2.db").exists()) {
                dbFile = getWebInf();
            } else {
                dbFile = null;
            }
        }
        if (dbFile == null) {
            dbFile = "./admin";
        }
        return dbFile;
    }

    private String getWebInf() {
        File file = PathUtils.getWebInfPath("data");

        if (new File(file, "admin.h2.db").exists()) {
            return file.getAbsolutePath() + "/admin";
        }

        return null;

    }

    @IocBean(name = "admin")
    public Dao getDao() {

        try {
            Class.forName("org.h2.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Cannot find class org.h2.Driver", e);
        }
        DruidDataSourceProvider dataSourceProvider = new DruidDataSourceProvider();
        dataSourceProvider.setUrl("jdbc:h2:file:" + getDbFile());
        dataSourceProvider.setPassword("sa");
        dataSourceProvider.setUsername("sa");
        dataSourceProvider.setDriverClassName("org.h2.Driver");
        ZoomDao dao = new ZoomDao(dataSourceProvider.getDataSource(), true);
        dao.setNameAdapterMaker(new NameAdapterMakerWrap(new ToLowerCaseNameAdapter()));
        return dao;
    }
}
